package uml.GUI;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collection;
import java.util.HashMap;

import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.KeyStroke;

import uml.eventsystem.IObserver;
import uml.eventsystem.ISubject;
import uml.eventsystem.SubjectImpl;
import uml.eventsystem.events.UMLEventId;
import uml.util.UMLConstants;

public class UMLContextMenu extends JPopupMenu implements ActionListener, ISubject
{
	private HashMap<String, UMLEventId> eventIDLookupTable;
	private SubjectImpl m_subjImpl;
	
	/**
	 * Constructor for the context menu
	 */

	public UMLContextMenu()
	{
		eventIDLookupTable = new HashMap<String, UMLEventId>();
		m_subjImpl = new SubjectImpl(this);
		addMenuItem("Exit", UMLConstants.EXIT_STROKE, UMLEventId.APPLICATION_EXIT);
		addMenuItem("Cancel", UMLConstants.CANCEL_STROKE, UMLEventId.CANCEL_MENU);
		addMenuItem ("Delete", UMLConstants.DELETE_STROKE, UMLEventId.DELETE);
	}
	/**
	 * registers and observer for all the events this object uses
	 * @param observer
	 */
	
	public void registerEvents(IObserver observer) 
	{
		Collection<UMLEventId> eventIds = eventIDLookupTable.values();
		for(UMLEventId eventId : eventIds)
			addObserver(observer, eventId);
	}
	
	/**
	 * Adds menuItems to the context menu
	 * 
	 * @param name
	 * @param stroke
	 * @param event
	 */
	private void addMenuItem (String name, KeyStroke stroke, UMLEventId event)
	{
		JMenuItem item = new JMenuItem (name);
		item.addActionListener (this);
		item.setAccelerator (stroke);
		this.put (name, event);
		this.add (item);
	}
	
	/**
	 * adds a menu item to the context menu
	 * @param name
	 * @param event
	 */

	private void addMenuItem(String name, UMLEventId event)
	{
		JMenuItem item = new JMenuItem(name);
		item.addActionListener(this);
		eventIDLookupTable.put(name, event);
		add(item);
	}
	
	/**
	 * Puts an eventId into the lookup table
	 * @param name
	 * @param event
	 */
	
	public void put (String name, UMLEventId event)
	{
		eventIDLookupTable.put (name, event);
	}
	
	@Override
	public void actionPerformed(ActionEvent event) 
	{
		String menuName = event.getActionCommand();
		UMLEventId eventId = eventIDLookupTable.get(menuName);
		notifyObservers(eventId);
	}
	@Override
	public void addObserver(IObserver observer, UMLEventId eventId) 
	{
		m_subjImpl.addObserver(observer, eventId);
	}
	@Override
	public void removeObserver(IObserver observer, UMLEventId eventId) 
	{
		m_subjImpl.removeObserver(observer, eventId);
	}
	@Override
	public void notifyObservers(UMLEventId eventId) 
	{
		m_subjImpl.notifyObservers(eventId);
	}
}
